package com.rent.auth.config;

import com.alibaba.fastjson.JSON;
import com.rent.auth.pojo.AdminExtension;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.CollectionUtils;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    @Autowired
    private UserDetailsService userDetailsService;

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        String name = authentication.getName();
        Object principal = authentication.getPrincipal();
        AdminExtension data;
        if (principal instanceof AdminExtension) {
            data = (AdminExtension) principal;
        } else {// 默认不调用用户数据
            UserDetails userDetails = userDetailsService.loadUserByUsername(name);
            if (userDetails == null) return null;
            data = (AdminExtension) userDetails;
        }
        LinkedHashMap<String, Object> map = JSON.parseObject(JSON.toJSONString(data), LinkedHashMap.class);
        if (CollectionUtils.isEmpty(map)) return null;
        // 转化 authorities 中的列表数据类型
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            map.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
//        map.put("user_name", name);
        return map;
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        return super.extractAuthentication(map);
    }

}
